{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 百度AI开放平台"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 通用物体和场景识别\n",
    "* 接口描述\n",
    "> 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "\n",
    "* 请求示例\n",
    "> HTTP 方法：POST\n",
    "\n",
    "* 请求URL\n",
    "> https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\n",
    "\n",
    "* 鉴权认证机制(access_token)\n",
    "> 1. 获取Access Token\n",
    "> 2. 获取access_token示例代码:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.47bd5ed965008b0d0f25f96ffe0c1895.315360000.1963917731.282335-25869193', 'expires_in': 2592000, 'session_key': '9mzdWTsQ/inv3KVjk49dZnLxPjFCGZTYYSWN2W4GPql6h6T/EolCBo72sL6jtTfaDUncopnJnxuf4bOzrEO3u/ms6kcJfA==', 'access_token': '24.bac9afd6c9c5846cc87b0230565f96be.2592000.1651149731.282335-25869193', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': 'f16edc077c059c1241ee1f59103cd2d7'}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "# 准备url参数（酬载）\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'SElglyZye9HnLyXPMpWd8Sy1',\n",
    "    'client_secret':'iKRKwiqlGhp28dRsW70B6BU4LkjD8D8q'\n",
    "    \n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())\n",
    "    access_token = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.bac9afd6c9c5846cc87b0230565f96be.2592000.1651149731.282335-25869193'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '天空', 'score': 0.287564, 'root': '自然风景-天空', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%A4%A9%E7%A9%BA/5534', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/241f95cad1c8a7868fa019076909c93d70cf5034', 'description': '天空，汉语词汇，拼音tiān kōng，谓天际空阔；日月星辰罗列的广大空间。是地球重要的组成部分，在古代中国有天圆地方的说法。人可以在天空观测气象或天文现象，从而得知天气变化、时间的流逝或自己的方位。日出日落可知一日中的时间，晚上月亮的盈亏可以知道一个月的时间。北斗星可以指示北方。云的厚度和形状可以知道会否下雨。 在天空可以欣赏到许多美丽的现象，如彩虹、极光和流星雨等。雀鸟会在天空飞翔。 由于石油等化石性燃料使用的增加而产生的悬浮质，特别是那些会在燃烧后释放二氧化硫的煤等燃料的影响，自1973年以来，除了欧洲，天空的能见度正在逐步降低。'}}, {'keyword': '飞机', 'score': 0.212465, 'root': '交通工具-飞机', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%A3%9E%E6%9C%BA/70237', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/faf2b2119313b07e5923b5660fd7912396dd8cc6', 'description': '飞机(aeroplane,airplane)是指具有一具或多具发动机的动力装置产生前进的推力或拉力，由机身的固定机翼产生升力，在大气层内飞行的重于空气的航空器。飞机是20世纪初最重大的发明之一，公认由美国人莱特兄弟发明。他们在1903年12月17日进行的飞行作为“第一次重于空气的航空器进行的受控的持续动力飞行”被国际航空联合会(FAI)所认可，同年他们创办了“莱特飞机公司”。自从飞机发明以后，飞机日益成为现代文明不可缺少的工具。它深刻的改变和影响了人们的生活，开启了人们征服蓝天历史。'}}, {'keyword': '风景', 'score': 0.143414, 'root': '自然风景-其他', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%A3%8E%E6%99%AF/645', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/574e9258d109b3de52a41f13c6bf6c81800a4cb6', 'description': '风景指的是供观赏的自然风光、景物，包括自然景观,人文景观。风景是由光对物的反映所显露出来的一种景象。犹言风光,景物、景色等，含义广泛。在中国古书上，尤其纯文艺作品的诗文方面，更是延用已久，甚至写景多于言情，几乎和旅游打成一片。而且还有一大部分作品是借景抒情，寓情于景。'}}, {'keyword': '图画', 'score': 0.07367, 'root': '商品-绘画', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%9B%BE%E7%94%BB/3357821', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/a8773912b31bb05191a21521387adab44aede031', 'description': '图画，汉语词语，读音是tú huà，意思是绘画。'}}, {'keyword': '屏幕截图', 'score': 0.006482, 'root': '非自然图像-屏幕截图', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE/3634161', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/aa18972bd40735fa016882639c510fb30e240854', 'description': '所谓屏幕截图就是将电脑屏幕上的桌面、窗口、对话框、选项卡等屏幕元素保存为图片。在Windows下用户可以使用键盘上的“打印屏幕系统请求”(Print Screen)按键进行整个屏幕的截图和当前活动窗口的截图(按住Alt键的同时按下Print Screen键)，还可以借助专业的屏幕截图软件进行截图。'}}], 'log_id': 1508789812782195839}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# f = open('C:/Users/玖玖/python/2022/xihu.jpg', 'rb')#绝对路径\n",
    "f = open('xihu.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "#params = {\"image\":img}\n",
    "#access_token = '[调用鉴权接口获取的token]'\n",
    "#request_url = request_url + \"?access_token=\" + access_token\n",
    "#url的参数（酬载）\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 菜品识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'calorie': '60', 'has_calorie': True, 'name': '扇贝', 'probability': '0.49747', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%89%87%E8%B4%9D/1047097', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/55e736d12f2eb938faf95b5adb628535e4dd6f85', 'description': '扇贝属于软体动物门，扇贝科，是我国重要的贝类养殖品种。扇贝可食部分的主要营养成分为蛋白质，与鱼类、虾类相似，是一种集食、药、滋补为一体的重要水产食物。扇贝广泛分布于世界各海域。扇贝柱的干制品称为“干贝”，为名贵海珍品。'}}, {'calorie': '94', 'has_calorie': True, 'name': '蒸扇贝', 'probability': '0.450631', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%92%B8%E6%89%87%E8%B4%9D/12993781', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b90e7bec54e736d161039c5895504fc2d5626949', 'description': '蒸扇贝，扇贝蒸着吃。'}}, {'has_calorie': False, 'name': '蒜香银丝元贝', 'probability': '0.0305631', 'baike_info': {}}, {'has_calorie': False, 'name': '非菜', 'probability': '0.00284085', 'baike_info': {}}, {'calorie': '338', 'has_calorie': True, 'name': '粉丝', 'probability': '0.00192449', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%B2%89%E4%B8%9D/27840', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b812c8fcc3cec3fd731dbd36db88d43f87942755', 'description': '粉丝是中国常见的食品之一，是一种用绿豆、红薯淀粉等做成的丝状食品，故名粉丝。往往又叫做粉条丝、冬粉(主要在台湾)。最好的粉丝是以绿豆制成，也可由玉米淀粉或者地瓜淀粉制作，但品质不如绿豆粉丝，因绿豆中的直链淀粉最多，煮时不易烂，口感最为滑腻。类似细面条状，干燥后贩卖，食用前最好先泡水让它柔软，粉丝的直径一般在0.5毫米左右，这也是它有“丝”之名的由来。'}}], 'log_id': 1508788942638494563}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('haixiang.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, params=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
